"""
测试数据验证工具
用于验证CSV测试数据的有效性
"""
import csv
import os
from config.constants import DATA_PATH


class DataValidator:
    """测试数据验证器"""

    @staticmethod
    def validate_csv_data(filepath, required_columns=None):
        """
        验证CSV文件数据的有效性
        Args:
            filepath: CSV文件路径
            required_columns: 必需的列名列表
        Returns:
            dict: 验证结果
        """
        result = {
            'valid': True,
            'errors': [],
            'warnings': [],
            'data_count': 0
        }

        full_path = os.path.join(DATA_PATH, filepath)

        # 检查文件是否存在
        if not os.path.exists(full_path):
            result['valid'] = False
            result['errors'].append(f"文件不存在: {filepath}")
            return result

        try:
            with open(full_path, 'r', encoding='utf-8') as f:
                reader = csv.DictReader(f)
                headers = reader.fieldnames

                # 检查必需列
                if required_columns:
                    missing_columns = set(required_columns) - set(headers)
                    if missing_columns:
                        result['valid'] = False
                        result['errors'].append(f"缺少必需列: {missing_columns}")

                # 验证数据行
                data_rows = list(reader)
                result['data_count'] = len(data_rows)

                if result['data_count'] == 0:
                    result['warnings'].append("CSV文件没有数据行")

                # 检查空值
                for i, row in enumerate(data_rows, 1):
                    for col, value in row.items():
                        if not value or value.strip() == '':
                            result['warnings'].append(f"第{i}行 {col} 列为空")

        except Exception as e:
            result['valid'] = False
            result['errors'].append(f"读取文件时出错: {str(e)}")

        return result

    @staticmethod
    def validate_login_data(filepath="data.csv"):
        """验证登录测试数据"""
        return DataValidator.validate_csv_data(
            filepath,
            required_columns=['username', 'password', 'expected_status']
        )


if __name__ == "__main__":
    # 验证登录数据
    result = DataValidator.validate_login_data()
    print("验证结果:", result)
